import {
  Controller,
  Get,
  HttpStatus,
  Param,
  Post,
  Request,
  Res,
  UploadedFile,
  UseInterceptors,
} from '@nestjs/common';
import * as fs from 'fs';
import { Response } from 'express';
import FileService from '../service/file.service';
import R from 'libs/common/utils/R';
import { FileInterceptor } from '@nestjs/platform-express';
import { diskStorage } from 'multer';
import { extname } from 'path';
import config from '../../config';
import { randomUUID } from 'crypto';
import BusinessError from 'libs/common/utils/BusinessError';

@Controller('/file')
export default class FileController {
  constructor(private readonly fileService: FileService) {}

  @Post('/upload')
  @UseInterceptors(
    FileInterceptor('file', {
      storage: diskStorage({
        destination: config.dir,
        filename: function (req, file, cb) {
          cb(null, randomUUID() + extname(file.originalname));
        },
      }),
    }),
  )
  async uploadFile(
    @Request() request,
    @UploadedFile() file,
  ): Promise<R<string>> {
    const uri = 'http://127.0.0.1:' + config.port;
    return R.ok(uri + '/file/' + file.filename);
  }
  
  @Post('/delete/:fileName')
  async delFile(@Param('fileName') fileName: string): Promise<R<any>> {
    const path = config.dir + '/' + fileName;
    // 检查文件是否存在
    if (!fs.existsSync(path)) {
      throw new BusinessError('文件未找到！', HttpStatus.NOT_FOUND);
    }
    fs.unlinkSync(path);
    return R.ok();
  }

  @Get('/:fileName')
  async readFile(@Param('fileName') fileName: string, @Res() res: Response) {
    const path = config.dir + '/' + fileName;
    // 检查文件是否存在
    if (!fs.existsSync(path)) {
      throw new BusinessError('文件未找到！', HttpStatus.NOT_FOUND);
    }
    res.setHeader('Content-disposition', `attachment; filename=${fileName}`);
    const readStream = fs.createReadStream(path);
    readStream.pipe(res);

    readStream.on('error', () => {
      throw new BusinessError(
        '读取文件失败！',
        HttpStatus.INTERNAL_SERVER_ERROR,
      );
    });

    readStream.on('end', () => {
      console.log('文件传输完成');
      // 这里可以添加其他清理工作，例如关闭数据库连接等
    });
  }
}
